package com.zftlive.springbooot.main.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.text.SimpleDateFormat;

/**
 * 服务启动监听器
 *
 * @author zengfantian
 * @version 1.0
 */
@Component
@Slf4j
public class ApplicationStartListener implements ApplicationListener<WebServerInitializedEvent> {

    /**
     * 日志标识
     */
    protected String TAG = this.getClass().getName()+".";

    /**
     * 域名或ip
     */
    private String host = "";

    /**
     * 端口
     */
    private int serverPort;

    /**
     * 启动时间
     */
    private String initDateTime = "";

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();

        log.info(TAG + "serverPort-->"+serverPort);
        try{
            SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateTime = dateFm.format(event.getTimestamp());
            this.initDateTime = dateTime;
        }catch (Throwable e){
            e.printStackTrace();
        }

        log.info(TAG + "server initDateTime-->"+initDateTime);
    }

    /**
     * 获取本机服务Host
     * @return
     */
    public String getHost(){
        try {
            InetAddress address = InetAddress.getLocalHost();
            this.host = address.getHostAddress();

        } catch (Throwable e) {
            e.printStackTrace();
        }

        log.info(TAG + "server host-->"+host);

        return host;
    }

    /**
     * 获取服务启动端口
     *
     * @return
     */
    public int getServerPort(){
        return serverPort;
    }

    /**
     * 获取服务启动初始化时间
     *
     * @return
     */
    public String getServerStartDateTime(){
        return initDateTime;
    }
}
